#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/un.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>

#define MSG		"Hello Client!"
#define IP		"127.0.0.1"
#define LISTEN_BACK_LOG	20

int main()
{
	int s_fd, c_fd;
	struct sockaddr_in	s_addr;
	struct sockaddr_in	c_addr;
	socklen_t	c_addr_len;
	
	// 1. create a socket
	s_fd = socket(AF_INET, SOCK_STREAM, 0);
	if(s_fd == -1) { perror("sock error"); exit(-1);}
	
	// 2. bind address
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(8080);
	if(inet_aton(IP,&(s_addr.sin_addr)) == -1) { perror("ip addr failed"); exit(-1);}
	if(bind(s_fd, (struct sockaddr *) &s_addr, sizeof(s_addr))){
		perror("bind error");
		exit(-1);
	}

	printf("server is waiting ...\n");
	// 3. listen
	if(listen(s_fd, LISTEN_BACK_LOG) == -1){ perror("listen error"); exit(-1);}
	
	// 4. accept
	c_fd = accept(s_fd, (struct sockaddr *)&c_addr, &c_addr_len);
	if(c_fd == -1){ perror("accept failed"); exit(-1); }
	
	// 5. ops
	//write(c_fd, MSG, sizeof(MSG));
	send(c_fd, MSG, sizeof(MSG), 0);
	// 6. close
	close(c_fd);
	close(s_fd);

	return 0;
}
